package raft.rpc;

import com.alipay.remoting.BizContext;
import com.sun.org.apache.xerces.internal.impl.xs.opti.DefaultNode;
import raft.entity.AentryParam;
import raft.entity.ClientKVReq;
import raft.entity.RvoteParam;
import raft.service.impl.NodeImpl;

import java.io.Serializable;

public class DefaultRpcServer implements RpcServer {

    private volatile boolean flag;

    private NodeImpl node ;

    private com.alipay.remoting.rpc.RpcServer rpcServer;

    public DefaultRpcServer(int port, NodeImpl node){
        if(flag){
            return;
        }
        synchronized (this){
            if(flag){
                return;
            }

            rpcServer = new com.alipay.remoting.rpc.RpcServer(port,false,false);
            rpcServer.registerUserProcessor(new RaftUserProcessor<Request>() {
                @Override
                public Object handleRequest(BizContext bizContext, Request request) throws Exception {
                    return handlerRequest(request);
                }
            });


            this.node = node;
            flag = true;
        }
    }

    @Override
    public void start() {

        System.out.println("rpc..."+ rpcServer.start());
    }

    @Override
    public void stop() {
        rpcServer.stop();
    }

    @Override
    public Response handlerRequest(Request request) {
        if (request.getCmd() == Request.R_VOTE) {
            return new Response(node.handleReqVote((RvoteParam) request.getObj()));
        } else if (request.getCmd() == Request.A_ENTRIES) {
            return new Response(node.handleAppendEntries((AentryParam) request.getObj()));
        } else if (request.getCmd() == Request.CLIENT_REQ) {
            return new Response(node.handlerClientRequest((ClientKVReq) request.getObj()));
        }
        return null;
    }
}
